package com.domor.xxx.system.service;

import com.domor.xxx.common.core.domain.TreeEntity;
import com.domor.xxx.common.core.domain.Ztree;
import com.domor.xxx.common.utils.StringUtils;
import com.domor.xxx.system.domain.SysMenu;
import com.domor.xxx.system.domain.SysRole;
import com.domor.xxx.system.domain.SysUser;
import com.domor.xxx.system.mapper.SysMenuMapper;
import com.domor.xxx.system.mapper.SysRoleMenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <h3>菜单管理 服务层</h3>
 *
 * @author liyuyang
 * @date 2020/4/23
 **/
@Service
public class SysMenuService {

    @Autowired
    private SysMenuMapper menuMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;

    /**
     * 根据用户查询菜单（首页左侧菜单）
     *
     * @param user 用户信息
     * @return 菜单列表
     */
    public List<SysMenu> selectMenusByUser(SysUser user) {
        List<SysMenu> menus = new LinkedList<SysMenu>();
        // 管理员显示所有菜单信息
        if (user.isAdmin()) {
            menus = menuMapper.selectMenuNormalAll();
        } else {
            menus = menuMapper.selectMenusByUserId(user.getUserId());
        }
        return toTreeList(menus);
    }

    /**
     * 查询菜单集合
     *
     * @return 所有菜单信息
     */
    public List<SysMenu> selectMenuList() {
        List<SysMenu> menus = menuMapper.selectMenuAll();
        return toTreeList(menus);
    }

    /**
     * 把菜单列表list转成tree list
     */
    private List<SysMenu> toTreeList(List<SysMenu> menus) {
        List<SysMenu> result = new ArrayList<>();
        for (SysMenu menu : menus) {
            if (menu.getParentId() == 0) {
                List<SysMenu> children = getChildren(menus, menu.getMenuId());
                menu.setChildren(children);
                result.add(menu);
            }
        }
        return result;
    }

    /**
     * 根据父ID获取所有子菜单（包含按钮）
     */
    private List<SysMenu> getChildren(List<SysMenu> menus, Long parentId) {
        List<SysMenu> result = new ArrayList<>();
        for (SysMenu menu : menus) {
            if (menu.getParentId().longValue() == parentId) {
                List<SysMenu> children = getChildren(menus, menu.getMenuId());
                menu.setChildren(children);
                result.add(menu);
            }
        }
        return result;
    }

    /**
     * 根据用户ID查询权限(shiro UserRealm授权)
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    public Set<String> selectPermsByUserId(Long userId) {
        List<String> perms = menuMapper.selectPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 根据角色ID查询菜单
     *
     * @param roleId 角色ID
     * @return 菜单列表
     */
    public List<TreeEntity> roleMenuTree(Long roleId) {
        List<TreeEntity> trees = new ArrayList<TreeEntity>();
        List<SysMenu> menuList = menuMapper.selectMenuAll();
        if (StringUtils.isNotNull(roleId)) {
            List<Long> roleMenuList;
            if (SysRole.isAdmin(roleId)) {
                roleMenuList = menuList.stream().map(SysMenu::getMenuId).collect(Collectors.toList());
            } else {
                roleMenuList = roleMenuMapper.selectMenuIdsByRoleId(roleId);
            }
            trees = initTree(menuList, 0L, roleMenuList);
        } else {
            trees = initTree(menuList, 0L, null);
        }
        return trees;
    }

    /**
     * 查询所有菜单树 TreeEntity
     * @return List<TreeEntity> 菜单树
     */
    public List<TreeEntity> menuTree() {
        List<SysMenu> menuList = menuMapper.selectMenuNormalAll();
        List<TreeEntity> trees = initTree(menuList, 0L, null);
        return trees;
    }

    /**
     * 递归，获取树List<TreeEntity>
     */
    private List<TreeEntity> initTree(List<SysMenu> menuList, Long parentId, List<Long> roleMenuList) {
        List<TreeEntity> trees = new ArrayList<>();
        boolean isCheck = StringUtils.isNotNull(roleMenuList);
        for (SysMenu menu : menuList) {
            if (menu.getParentId().longValue() == parentId) {
                TreeEntity tree = new TreeEntity();
                tree.setId(menu.getMenuId().intValue());
                tree.setText(menu.getMenuName());
                tree.setAttributes(menu.getMenuType());

                List<TreeEntity> children = initTree(menuList, menu.getMenuId(), roleMenuList);
                tree.setChildren(children);

                if (isCheck && children.isEmpty()) {
                    tree.setChecked(roleMenuList.contains(menu.getMenuId()));
                }
                trees.add(tree);
            }
        }
        return trees;
    }

    /**
     * 根据角色ID查询菜单
     *
     * @param role 角色对象
     * @return 菜单列表
     */
    public List<Ztree> roleMenuTreeData(SysRole role) {
        Long roleId = role.getRoleId();
        List<Ztree> trees = new ArrayList<Ztree>();
        List<SysMenu> menuList = menuMapper.selectMenuAll();
        if (StringUtils.isNotNull(roleId)) {
            List<Long> roleMenuList = roleMenuMapper.selectMenuIdsByRoleId(roleId);
            trees = initZtree(menuList, roleMenuList);
        } else {
            trees = initZtree(menuList, null);
        }
        return trees;
    }

    /**
     * 查询所有菜单(不包含按钮)
     *
     * @return 菜单列表
     */
    public List<Ztree> menuTreeData() {
        List<SysMenu> menuList = menuMapper.selectMenuNormalAll();
        List<Ztree> trees = initZtree(menuList, null);
        return trees;
    }

    /**
     * 对象转菜单树
     *
     * @param menuList     菜单列表
     * @param roleMenuList 角色已存在菜单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<SysMenu> menuList, List<Long> roleMenuList) {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleMenuList);
        for (SysMenu menu : menuList) {
            Ztree ztree = new Ztree();
            ztree.setId(menu.getMenuId());
            ztree.setPId(menu.getParentId());
            ztree.setName(menu.getMenuName());
            ztree.setTitle(menu.getMenuName());
            if (isCheck) {
                ztree.setChecked(roleMenuList.contains(menu.getMenuId()));
            }
            ztrees.add(ztree);
        }
        return ztrees;
    }

    /**
     * 删除菜单管理信息
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    public int deleteMenuById(Long menuId) {
        return menuMapper.deleteMenuById(menuId);
    }

    /**
     * 根据菜单ID查询信息
     *
     * @param menuId 菜单ID
     * @return 菜单信息
     */
    public SysMenu selectMenuById(Long menuId) {
        return menuMapper.selectMenuById(menuId);
    }

    /**
     * 查询子菜单数量
     *
     * @param parentId 父级菜单ID
     * @return 结果
     */
    public int selectCountMenuByParentId(Long parentId) {
        return menuMapper.selectCountMenuByParentId(parentId);
    }

    /**
     * 查询菜单使用数量
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    public int selectCountRoleMenuByMenuId(Long menuId) {
        return roleMenuMapper.selectCountRoleMenuByMenuId(menuId);
    }

    /**
     * 新增保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public int insertMenu(SysMenu menu) {
        return menuMapper.insertMenu(menu);
    }

    /**
     * 修改保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public int updateMenu(SysMenu menu) {
        return menuMapper.updateMenu(menu);
    }

    /**
     * 校验菜单名称是否唯一
     *
     * @param menu 菜单信息
     * @return 结果 boolean
     */
    public boolean checkMenuNameUnique(SysMenu menu) {
        Long menuId = StringUtils.isNull(menu.getMenuId()) ? -1L : menu.getMenuId();
        SysMenu info = menuMapper.checkMenuNameUnique(menu.getMenuName(), menu.getParentId());
        if (StringUtils.isNotNull(info) && info.getMenuId().longValue() != menuId.longValue()) {
            return true;
        }
        return false;
    }

}
